package com.bst.web.etl;

import com.bst.common.annotation.Log;
import com.bst.common.constant.DwFieldConstants;
import com.bst.common.core.controller.BaseController;
import com.bst.common.core.domain.AjaxResult;
import com.bst.common.enums.BusinessType;
import com.bst.common.utils.DateUtil;
import com.bst.common.utils.StringUtils;
import com.bst.common.utils.poi.ExcelUtil;
import com.bst.common.vo.HeaderAndBodyVO;
import com.bst.etl.domain.EtlDrawDm;
import com.bst.etl.service.IEtlDrawDmService;
import com.bst.etl.service.IEtlQryDmPubChartService;
import com.bst.etl.service.IEtlQryDmPubService;
import com.bst.etl.utils.IndexQueryUtil;
import com.bst.etl.vo.DmQueryIndexVO;
import com.bst.etl.vo.DmQueryParamVO;
import com.bst.etl.vo.chart.*;
import com.bst.md.domain.MdIndex;
import com.bst.md.service.IMdIndexService;
import com.bst.system.vo.IndexWallParamVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/base/etl/query/dm")
public class EtlDmPubQueryController extends BaseController {

    @Autowired
    IEtlQryDmPubService etlDmQueryService;
    @Autowired
    IEtlQryDmPubChartService etlQryDmPubChartService;
    @Autowired
    IMdIndexService mdIndexService;
    @Autowired
    IEtlDrawDmService etlDrawDmService;

    @ApiOperation(value="自助查询")
    @GetMapping("/self")
    public String exec(String type, ModelMap mmap)
    {
        mmap.put("defChartType",type);
        return "etl/query/dm/selfForDm";
    }

    @ApiOperation(value="天数据看板")
    @GetMapping(value="/dayIndexData")
    public String dayIndexData() {
        return "etl/query/index_board/dayData";
    }

    @ApiOperation(value="月度看板")
    @GetMapping(value="/monthIndexData")
    public String monthIndexData() {
        return "etl/query/index_board/monthData";
    }

    @ApiOperation(value="年度看板")
    @GetMapping(value="/yearIndexData")
    public String yearIndexData() {
        return "etl/query/index_board/yearData";
    }

    @ApiOperation(value="指标综合查询-分页")
    @RequestMapping(value="/commonDmQuery", method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult commonDmQuery(@RequestBody DmQueryParamVO paramVO) {
        AjaxResult result = etlDmQueryService.findIndexDataWithHeader(paramVO);
        return result;
    }

    @Log(title = "指标综合查询导出", businessType = BusinessType.EXPORT)
    @PostMapping("/commonDmQuery/export")
    @ResponseBody
    public AjaxResult commonDmQueryExport(@RequestBody DmQueryParamVO paramVO)
    {
        AjaxResult result = this.commonDmQuery(paramVO);
        HeaderAndBodyVO vo = (HeaderAndBodyVO)result.get(AjaxResult.DATA_TAG);
        String fileName = new ExcelUtil().createExcel(vo,paramVO.getFileName(),"Sheet");
        return AjaxResult.success(fileName);
    }

    @ApiOperation(value="指标墙数据查询")
    @GetMapping(value="/indexWall/sunIndex")
    @ResponseBody
    public AjaxResult querySunIndexData(String idIndex,String qDes) throws ParseException {
        EtlDrawDm dm = etlDrawDmService.selectEtlDrawDmByIdIndex(idIndex);
        if(dm==null) {
            return AjaxResult.error("指标未配置");
        }
        String relyIdIndexs = dm.getTbRelys();
        if(StringUtils.isNotEmpty(relyIdIndexs)) {
            String idIndexs[] = relyIdIndexs.split(",");
            List<MdIndex> indexList = mdIndexService.findByIds(Arrays.asList(idIndexs),null,null);
            DmQueryParamVO paramVO = new DmQueryParamVO();
            paramVO.setDateType("Q");
            paramVO.setStartDate(indexWallDateInterval(qDes,"Q"));
            paramVO.setEndDate(qDes);
            paramVO.setOrderBy(" ID_DIM_DAY_OCCUR asc ");
            return etlDmQueryService.generateIndexWall(indexList,paramVO);
        }
        return AjaxResult.error("指标未配置");
    }

    @PostMapping(value="/indexWall/query")
    @ResponseBody
    public AjaxResult aa (@RequestBody IndexWallParamVO wallParamVO) throws ParseException {
        List<MdIndex> indexList = mdIndexService.selectIndexWall(wallParamVO);
        DmQueryParamVO paramVO = new DmQueryParamVO();
        String startDate = wallParamVO.getStartDate();
        paramVO.setStartDate(startDate);
        paramVO.setDateType(wallParamVO.getDateType());
        List<IndexWallVO> wallVOS = new ArrayList<>();
        IndexWallVO wallVO;
        Map<String,Object> dataMap;
        for (MdIndex mdIndex : indexList) {
            //指标值、同环比值
            paramVO.setIdIndex(mdIndex.getIdIndex());
            paramVO.setFgHb(true);
            paramVO.setFgTb(true);
            List<Map<String,Object>> list = etlDmQueryService.findSingleIndexData(paramVO);
            wallVO = new IndexWallVO();
            if(list!=null && list.size()>0) {
                dataMap = list.get(0);
                wallVO.setValue(IndexQueryUtil.resultHandler(dataMap.get(mdIndex.getIdIndex()),mdIndex.getSdValtp()));
                wallVO.setYoy(IndexQueryUtil.resultHandler(dataMap.get(DwFieldConstants.FIELD_YOY),mdIndex.getSdValtp()));
                wallVO.setYoyRate(IndexQueryUtil.resultHandler(dataMap.get(DwFieldConstants.FIELD_YOY_RATE),mdIndex.getSdValtp()));
                wallVO.setMom(IndexQueryUtil.resultHandler(dataMap.get(DwFieldConstants.FIELD_MOM),mdIndex.getSdValtp()));
                wallVO.setMomRate(IndexQueryUtil.resultHandler(dataMap.get(DwFieldConstants.FIELD_MOM_RATE),mdIndex.getSdValtp()));
            }
            paramVO.setFgHb(false);
            paramVO.setFgTb(false);
            //各指标折线数据
            paramVO.setEndDate(paramVO.getStartDate());
            paramVO.setStartDate(indexWallDateInterval(startDate,wallParamVO.getDateType()));
            paramVO.setOrderBy(" ID_DIM_DAY_OCCUR asc ");
            List<Map<String,Object>> chartList = etlDmQueryService.findSingleIndexData(paramVO);
            wallVO.setChartList(chartList);
            //不可累加的复合指标需计算子指标值
            if(mdIndex.getFgAccu()==0 && mdIndex.getEuTp()==1) {

            }
            wallVOS.add(wallVO);
        }
        return AjaxResult.success(wallVOS);
    }

    @ApiOperation(value="指标墙数据查询")
    @ResponseBody
    public AjaxResult queryIndexForWall(@RequestBody IndexWallParamVO wallParamVO) throws ParseException {
        List<MdIndex> indexList = mdIndexService.selectIndexWall(wallParamVO);
        String startDate = wallParamVO.getStartDate();
        DmQueryParamVO paramVO = new DmQueryParamVO();
        paramVO.setDateType(wallParamVO.getDateType());
        paramVO.setStartDate(indexWallDateInterval(startDate,wallParamVO.getDateType()));
        paramVO.setEndDate(startDate);
        paramVO.setOrderBy(" ID_DIM_DAY_OCCUR asc ");
        List<DmQueryIndexVO> indexVOS = new ArrayList<>();
        AjaxResult result;
        ChartParamVO shapeParamVO = new ChartParamVO();
        ChartStyleVO styleVO = new ChartStyleVO();
        styleVO.setChartType("line");
        styleVO.setChartXVO(new ChartXVO("ID_DIM_DAY_OCCUR"));
        List<ChartYVO> chartYVOList = new ArrayList<>();
        List<IndexWallVO> wallVOS = new ArrayList<>();
        IndexWallVO wallVO;
        for (MdIndex index:indexList) {
            wallVO = new IndexWallVO();
            wallVO.setNaIndex(index.getNa());
            wallVO.setIdIndex(index.getIdIndex());
            wallVOS.add(wallVO);
            indexVOS.clear();
            chartYVOList.clear();
            indexVOS.add(new DmQueryIndexVO(index.getIdIndex()));
            paramVO.setIndexVOS(indexVOS);
            shapeParamVO.setDmQueryParamVO(paramVO);
            shapeParamVO.setChartStyleVO(styleVO);
            styleVO.setTitle(index.getNa());
            chartYVOList.add(new ChartYVO(index.getIdIndex(),index.getUnit()));
            styleVO.setChartYVOList(chartYVOList);
            result = etlDmQueryService.findIndexDataWithHeader(shapeParamVO.getDmQueryParamVO());
            if(!AjaxResult.isSuccess(result)) {
                return result;
            }
            HeaderAndBodyVO headerAndBodyVO = (HeaderAndBodyVO)result.get("data");
            if(headerAndBodyVO!=null) {
                result = etlQryDmPubChartService.generateBaseShape(headerAndBodyVO,shapeParamVO.getChartStyleVO());
                if(AjaxResult.isSuccess(result)) {
                    Object data = ((ChartResultVO)result.get(AjaxResult.DATA_TAG)).getData();
                    wallVO.setShapeData(data==null?"":data.toString());
                }
            }
        }
        return AjaxResult.success(wallVOS);
    }

    private String indexWallDateInterval(String startDate,String dateType) throws ParseException {
        if("D".equals(dateType)) {
            String day=startDate.replaceAll("-","");
            Date date = DateUtil.FORMAT_YYYY_MM_DD.parse(day);
            Date sevenDateAgo = DateUtil.calculate(date, Calendar.DAY_OF_MONTH,-7);
            return DateUtil.FORMAT_YYYY_MM_DD.format(sevenDateAgo);
        } else if("M".equals(dateType)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            Date date = format.parse(startDate);
            Date sevenDateAgo = DateUtil.calculate(date, Calendar.MONTH,-6);
            return format.format(sevenDateAgo);
        } else if("Y".equals(dateType)) {
            String day=startDate.replaceAll("-","");
            return (Integer.parseInt(startDate)-1)+"";
        } else if("Q".equals(dateType)) { //显示一年数据，即4个季度 2024-1
            Integer year = Integer.parseInt(startDate.substring(0,4));
            return year+""+startDate.substring(4,5);
        }
        return null;
    }
}
